package com.nnnu.wsnackshop.controller.admin;

import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.pojo.dto.AddCategoryDTO;
import com.nnnu.wsnackshop.pojo.dto.CategoryPageDTO;
import com.nnnu.wsnackshop.pojo.dto.UpdateCategoryDTO;
import com.nnnu.wsnackshop.pojo.vo.CategoryVO;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.ICategoriesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 商品分类 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("adminCategoriesController")
@RequestMapping("/api/admin/categories")
@Tag(name = "管理端-分类接口")
@Slf4j
@Validated
@RequiredArgsConstructor
@CacheConfig(cacheNames = "categories")
public class CategoriesController {
    private final ICategoriesService categoryService;

    @Operation(summary = "分页查询分类")
    @GetMapping("/page")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("category:read")
    public Result<?> pageCategories(@Valid @ParameterObject CategoryPageDTO dto) {
        log.info("分页查询分类: {}", dto);
        return Result.success(categoryService.pageCategories(dto), MessageConstants.SELECT_OK);
    }

    @Operation(summary = "分类树结构")
    @GetMapping("/tree")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("category:read")
    public Result<?> categoryTree() {
        log.info("查询分类树结构");
        return Result.success(categoryService.getCategoryTree(), MessageConstants.SELECT_OK);
    }

    @Operation(summary = "新增分类")
    @PostMapping
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:create")
    @CacheEvict(value = "categories", allEntries = true)
    public Result<?> addCategory(@Valid @RequestBody @Parameter(description = "新增分类 DTO") AddCategoryDTO dto) {
        log.info("新增分类: {}", dto);
        categoryService.addCategory(dto);
        return Result.success(MessageConstants.ADD_OK);
    }

    @Operation(summary = "更新分类")
    @PutMapping
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:update")
    @CacheEvict(value = "categories", allEntries = true)
    public Result<Void> updateCategory(@Valid @RequestBody @Parameter(description = "更新分类 DTO") UpdateCategoryDTO dto) {
        log.info("更新分类: {}", dto);
        categoryService.updateCategory(dto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "删除分类")
    @DeleteMapping("/{id}")
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:delete")
    @CacheEvict(value = "categories", allEntries = true)
    public Result<Void> deleteCategory(
            @PathVariable @Parameter(description = "分类 ID", in = ParameterIn.PATH) Integer id) {
        log.info("删除分类: {}", id);
        categoryService.deleteCategory(id);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "修改分类状态")
    @PutMapping("/{id}/status/{status}")
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:update")
    @CacheEvict(value = "categories", allEntries = true)
    public Result<Void> updateStatus(@PathVariable @Parameter(description = "分类 ID", in = ParameterIn.PATH) Integer id,
            @PathVariable @Parameter(description = "状态", in = ParameterIn.PATH) Integer status) {
        log.info("更新分类状态: id={}, status={}", id, status);
        categoryService.updateStatus(id, status);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "获取顶级分类（大类）")
    @GetMapping("/top")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("category:read")
    @Cacheable(value = "categories", key = "'top'")
    public Result<List<?>> getTopCategories() {
        log.info("获取顶级分类");
        return Result.success(categoryService.listTopCategories(), MessageConstants.SELECT_OK);
    }

    @Operation(summary = "修改分类排序")
    @PutMapping("/{id}/sort/{sort}")
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:update")
    @CacheEvict(value = "categories", allEntries = true)
    public Result<Void> updateSort(@PathVariable @Parameter(description = "分类 ID", in = ParameterIn.PATH) Integer id,
            @PathVariable @Parameter(description = "排序", in = ParameterIn.PATH) Integer sort) {
        log.info("更新分类排序: id={}, sort={}", id, sort);
        categoryService.updateSort(id, sort);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "分类详情")
    @GetMapping("/{id}")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("category:read")
    @Cacheable(value = "categories", key = "#id")
    public Result<CategoryVO> getDetail(
            @PathVariable @Parameter(description = "分类id", in = ParameterIn.PATH) Integer id) {
        log.info("查询分类详情: {}", id);
        return Result.success(categoryService.getCategoryDetail(id), MessageConstants.SELECT_OK);
    }

    @Operation(summary = "导出分类Excel", description = "仅 superAdmin 且拥有 category:export 权限可访问")
    @GetMapping("/export")
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:export")
    public void exportCategories(HttpServletResponse response) throws IOException {
        log.info("导出分类Excel");
        categoryService.exportCategories(response);
    }

    @Operation(summary = "导入分类Excel", description = "仅 superAdmin 且拥有 category:import 权限可访问")
    @PostMapping("/import")
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:import")
    @CacheEvict(value = "categories", allEntries = true)
    public Result<Void> importCategories(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("导入分类Excel");
        categoryService.importCategories(file);
        return Result.success(MessageConstants.ADD_OK);
    }

    @Operation(summary = "下载分类导入模板")
    @GetMapping("/template")
    @RequiresRoles("superAdmin")
    @RequiresPermissions("category:read")
    public void downloadTemplate(HttpServletResponse response) {
        log.info("下载分类导入模板");
        categoryService.downloadTemplate(response);
    }
}
